﻿using Common.Communication;
using Common.Device.DeviceDb;
using Common.Device.Enums;
using Common.Device.Interfaces;
using Common.Tool.DataTools;
using Common.Tool.Models;
using System;
using System.IO.Ports;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace TongXin
{
    public class RS232SerialPort : SerialPortBase, ITongXin
    {
        public string Name { get; set; }
        public RS232SerialPort(UseDevice device) : base(device.port, Convert.ToInt32(device.parameter), timeout: 1500)
        {
            Name = device.name;
        }
        public Result<byte[]> Receive(TongXinEnum.DataType type, int waitTime)
        {
            lock (this)
            {
                AppendInfo(Name, "读取返回值");
                Task.Delay(waitTime).Wait();
                var r = ReadBytes();
                if (r.IsSucceed == false)
                {
                    AppendTip(Name,r.Err);
                    return r;
                }
                AppendResult(Name, type == TongXinEnum.DataType.ASCII ? Encoding.ASCII.GetString(r.Value) : DataConvert.ByteArrayToString(r.Value));
                return r;
            }
        }

        public Result Send(TongXinEnum.DataType type, string buffer)
        {
            lock (this)
            {
                AppendInfo(Name, "发送指令"+ buffer);
                var r = Write(type == TongXinEnum.DataType.ASCII ? Encoding.ASCII.GetBytes(buffer) : DataConvert.StringToByteArray(buffer, false));
                if (r.IsSucceed == false)
                {
                    AppendTip(Name, r.Err);
                    return r;
                }
                AppendResult(Name, "发送成功");
                return r;
            }
        }

        public Result<byte[]> SendAndReceive(TongXinEnum.DataType type, string buffer, int waitTime)
        {
            lock (this)
            {
                AppendInfo(Name, "发送指令" + buffer);
                var r = WriteThenRead(type == TongXinEnum.DataType.ASCII ? Encoding.ASCII.GetBytes(buffer) : DataConvert.StringToByteArray(buffer, false),waitTime);
                if (r.IsSucceed == false)
                {
                    AppendTip(Name, r.Err);
                    return r;
                }
                AppendResult(Name, type == TongXinEnum.DataType.ASCII ? Encoding.ASCII.GetString(r.Value) : DataConvert.ByteArrayToString(r.Value));
                return r;
            }
        }
    }
}
